package com.jinlia.show.modules.wxapp.websocket;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class WebSocketService {


    /**
     * 发送消息
     *
     * @param userId 接收人id
     * @param text   内容
     * @return
     * @throws IOException
     */
    @SneakyThrows
    public Boolean sendMsg(String userId, String text)  {
        Set<WebSocketSessionManager.ChatWebSocketSession> chatWebSocketSessions = WebSocketSessionManager.SESSION_POOL.get(userId);
        for (WebSocketSessionManager.ChatWebSocketSession chatWebSocketSession : chatWebSocketSessions) {
            chatWebSocketSession.getWebSocketSession().sendMessage(new TextMessage(text));
        }
        return Boolean.TRUE;
    }

    /**
     * 广播消息
     *
     * @param text 消息内容
     * @return
     * @throws IOException
     */
    @SneakyThrows
    public void broadcastMsg(String text){
        if (CollectionUtils.isEmpty(WebSocketSessionManager.SESSION_POOL.values())) {
            return;
        }
        int countBroadcastMsg = 0;
        for (Set<WebSocketSessionManager.ChatWebSocketSession> value : WebSocketSessionManager.SESSION_POOL.values()) {
            for (WebSocketSessionManager.ChatWebSocketSession chatWebSocketSession : value) {
                countBroadcastMsg = countBroadcastMsg +1;
                chatWebSocketSession.getWebSocketSession().sendMessage(new TextMessage(text));
            }
        }
        log.info("广播数量为={}",countBroadcastMsg);
    }
}
